//
//  VideoHandle.m
//  BasketballClub
//
//  Created by lanou3g on 16/1/15.
//  Copyright © 2016年 孙鸿吉. All rights reserved.
//

#import "VideoHandle.h"
#import <AFNetworking.h>
#import "VideoModel.h"
#import "CoreDataManager.h"
static VideoHandle *handle = nil;
@implementation VideoHandle
///
+(instancetype)sharedVideoHandle
{
    return [[self alloc]init];
    
}
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (handle == nil) {
            handle = [super allocWithZone:zone];
        }
    });
    return handle;
}

///
-(void)getVideoDataFromNetWorkWithNumber:(NSInteger)number
                               withBlock:(VIDEOBLOCK)finishBlock
{
    NSString *urlString = [NSString stringWithFormat:@"http://api.basketball.app887.com/api/Articles.action?keyword=&npc=%ld&opc=20&type=视频集锦&uid=4467",number];
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlString]];
    AFHTTPSessionManager *sessionManger = [AFHTTPSessionManager manager];
    ///设置返回格式
    sessionManger.responseSerializer = [AFHTTPResponseSerializer serializer];
    ///GET请求
    ///parameters请求参数
    [sessionManger GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        NSDictionary *dict1 = dict [@"root"];
        
        NSArray *arr1 = dict1 [@"list"];
        if (self.VideoArray == nil) {
            self.VideoArray = [NSMutableArray array];
        }
       
        for (NSDictionary *dic in arr1) {
            VideoModel *model = [[VideoModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.VideoArray addObject:model];
            
            if ([[CoreDataManager shareCoreDateManager] selectAllVideoModel].count > self.VideoArray.count) {
                [[CoreDataManager shareCoreDateManager] deleteVideoAllData];
            }else{
                [[CoreDataManager shareCoreDateManager] insertVideoDataToSql:model];
            }
            
        }
        dispatch_async(dispatch_get_main_queue(),^{
            finishBlock(self.VideoArray.count > 0);
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败");
        self.VideoArray = [NSMutableArray arrayWithArray:[[CoreDataManager shareCoreDateManager] selectAllVideoModel]];

        dispatch_async(dispatch_get_main_queue(),^{
            finishBlock(self.VideoArray.count > 0);
        });


    }];
}
@end
